package api

import (
	"TaskAssignmentSystem/internal/admin/dao"
	"TaskAssignmentSystem/internal/admin/services"
	"TaskAssignmentSystem/internal/pkg/code"
	"TaskAssignmentSystem/internal/pkg/middleware/handler"
	"TaskAssignmentSystem/internal/pkg/middleware/mysqlhandler"
	"TaskAssignmentSystem/pkg/utils"
	"github.com/kataras/iris/v12"
	"strings"
)

// @Summary 管理员列表
// @Description 管理员列表
// @Tags 管理员
// @Accept application/json
// @Produce application/json
// @param Accept-Version header string true "1.0.0"
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param page query int64 true "分页页码"
// @Param page_size query int64 true "分页大小"
// @Success 200 {object} utils.Response --> 成功后返回数据结构
// @Failure 400 {object} utils.ResponseError --> 失败后返回数据结构
// @Router /admin/system_admin/list [get]
type SystemAdminListRequest struct {
	Page     int64 `json:"page" validate:"required"`
	PageSize int64 `json:"page_size" validate:"required"`
}

func SystemAdminListHandler(ctx iris.Context) {
	//page := ctx.URLParamInt64Default("page", 1)
	//pageSize := ctx.URLParamInt64Default("page_size", 20)

	var RequestParams IncomeQueryRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var systemAdminServe services.SystemAdminService
	if res, err := systemAdminServe.GetList(RequestParams.Page, RequestParams.PageSize); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		if _, typeList, err := systemAdminServe.SystemAdminTypeList(RequestParams.Page, RequestParams.PageSize); err != nil {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
			return
		} else {
			ctx.JSON(utils.Response{Code: iris.StatusOK, Message: "ok", Data: iris.Map{"count": res.Total, "list": res.Data, "adminTypeList": typeList}})
			return
		}
	}
}

type EditSystemAdminRequest struct {
	Id                 uint             `json:"id"`
	UserName           string           `json:"user_name"`
	PassWord           string           `json:"pass_word,omitempty"`
	NickName           string           `json:"nick_name"`
	AdminType          int              `json:"admin_type"`
	Status             int              `json:"status"`
	ProjectPermissions code.SliceString `json:"project_permissions"` //项目权限
	TeamPermissions    code.SliceString `json:"team_permissions"`    //团队权限
	ActionPermissions  code.SliceString `json:"action_permissions"`  //操作权、 "0" 全部权限 1查看权限 2上传权限 3 下载权限
}

// @Summary 编辑管理员
// @Description 编辑系统管理员
// @Tags 管理员
// @Accept application/json
// @Produce application/json
// @param Accept-Version header string true "1.0.0"
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param param body EditSystemAdminRequest true "编辑管理员参数"
// @Success 200 {object} utils.Response --> 成功后返回数据结构
// @Failure 400 {object} utils.ResponseError --> 失败后返回数据结构
// @Router /admin/system_admin/edit [post]
func EditSystemAdminHandler(ctx iris.Context) {
	var RequestParams EditSystemAdminRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var systemAdminServe services.SystemAdminService
	updateObj := map[string]interface{}{}
	if RequestParams.PassWord != "" {
		updateObj["pass_word"] = utils.MD5(RequestParams.PassWord)
	}
	updateObj["admin_type"] = RequestParams.AdminType
	updateObj["user_name"] = RequestParams.UserName
	updateObj["nick_name"] = RequestParams.NickName
	updateObj["status"] = RequestParams.Status
	updateObj["project_permissions"] = RequestParams.ProjectPermissions
	updateObj["team_permissions"] = RequestParams.TeamPermissions
	updateObj["action_permissions"] = RequestParams.ActionPermissions
	if err := systemAdminServe.Edit(RequestParams.Id, updateObj); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		ctx.JSON(utils.Response{Code: iris.StatusOK, Message: "ok", Data: "ok"})
		return
	}
}

type NewSystemAdminRequest struct {
	UserName           string           `json:"user_name" validate:"required"`
	PassWord           string           `json:"pass_word" validate:"required"`
	NickName           string           `json:"nick_name"`
	AdminType          int              `json:"admin_type"`
	Status             int              `json:"status"`
	ProjectPermissions code.SliceString `json:"project_permissions"` //项目权限
	TeamPermissions    code.SliceString `json:"team_permissions"`    //团队权限
	ActionPermissions  code.SliceString `json:"action_permissions"`  //操作权、 "0" 全部权限 1查看权限 2上传权限 3 下载权限
}

// @Summary 新建管理员
// @Description 创建一个新的系统管理员
// @Tags 管理员
// @Accept application/json
// @Produce application/json
// @param Accept-Version header string true "1.0.0"
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param param body NewSystemAdminRequest true "新建管理员参数"
// @Success 200 {object} utils.Response --> 成功后返回数据结构
// @Failure 400 {object} utils.ResponseError --> 失败后返回数据结构
// @Router /admin/system_admin/created [post]
func NewSystemAdminHandler(ctx iris.Context) {
	var RequestParams NewSystemAdminRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var systemAdminServe services.SystemAdminService
	var newSystemAdmin dao.SystemAdmin
	newSystemAdmin.UserName = RequestParams.UserName
	if RequestParams.PassWord != "" {
		newSystemAdmin.PassWord = utils.MD5(RequestParams.PassWord)
	}
	newSystemAdmin.NickName = RequestParams.NickName
	newSystemAdmin.AdminType = RequestParams.AdminType
	newSystemAdmin.Status = RequestParams.Status
	newSystemAdmin.ProjectPermissions = RequestParams.ProjectPermissions
	newSystemAdmin.TeamPermissions = RequestParams.TeamPermissions
	newSystemAdmin.ActionPermissions = RequestParams.ActionPermissions
	if err := systemAdminServe.Created(newSystemAdmin); err != nil {
		switch mysqlhandler.MysqlErrCode(err) {
		case mysqlhandler.ErrDuplicateEntryCode:
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: "账号已存在！"})
			return
		default:
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
			return
		}

	} else {
		ctx.JSON(utils.Response{Code: iris.StatusOK, Message: "ok", Data: "ok"})
		return
	}
}

// @Summary 获取管理员信息
// @Description 获取登录管理员的信息
// @Tags 管理员
// @Accept application/json
// @Produce application/json
// @param Accept-Version header string true "1.0.0"
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Success 200 {object} utils.Response --> 成功后返回数据结构
// @Failure 400 {object} utils.ResponseError --> 失败后返回数据结构
// @Router /admin/system_admin/info [get]
func AdminInfoHandler(ctx iris.Context) {
	var claims services.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	var systemAdminServe dao.Common[dao.SystemAdmin]
	if res, err := systemAdminServe.First(map[string]interface{}{"id": claims.Id}); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		/*ctx.JSON(utils.Response{Code: iris.StatusOK, Message: "ok", Data: res})
		return*/
		var systemPermissionDao dao.Common[dao.SystemPermission]
		if systemPermission, err := systemPermissionDao.FindAll(map[string]interface{}{}); err != nil {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
			return
		} else {
			var systemAdminPermissionDao dao.Common[dao.SystemAdminPermission]
			if systemAdminPermission, err := systemAdminPermissionDao.FindAll(map[string]interface{}{"admin_type_id": res.AdminType}); err != nil {
				ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
				return
			} else {
				for i, _ := range systemAdminPermission {
					for j, _ := range systemPermission {
						if systemAdminPermission[i].PermissionId == systemPermission[j].Id {
							systemAdminPermission[i].Pid = systemPermission[j].Pid
						}
					}
				}
				ctx.JSON(utils.Response{Code: iris.StatusOK, Message: "ok", Data: iris.Map{"adminInfo": res, "permission": systemPermission, "admin_permission": systemAdminPermission}})
				return
			}
		}

	}
}

type ChangeAdminStatusRequest struct {
	Id     uint `json:"id" validate:"required"`
	Status int  `json:"status"`
}

// @Summary 编辑管理员的状态
// @Description 编辑管理员的状态
// @Tags 管理员
// @Accept application/json
// @Produce application/json
// @param Accept-Version header string true "1.0.0"
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param param body ChangeAdminStatusRequest true "改变管理员的状态参数"
// @Success 200 {object} utils.Response --> 成功后返回数据结构
// @Failure 400 {object} utils.ResponseError --> 失败后返回数据结构
// @Router /admin/system_admin/change_status [post]
func ChangeAdminStatusHandler(ctx iris.Context) {
	var RequestParams ChangeAdminStatusRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var claims services.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	var common dao.Common[dao.SystemAdmin]
	if admin, err := common.First(map[string]interface{}{"id": RequestParams.Id}); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		if claims.Type >= admin.AdminType {
			ctx.JSON(utils.ResponseError{Code: 403, Message: "无法修改，权限不够！"})
			return
		} else {
			var adminServe services.SystemAdminService
			if err := adminServe.ChangeStatus(RequestParams.Id, RequestParams.Status); err != nil {
				ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
				return
			} else {
				ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: "ok"})
				return
			}
		}
	}
}

type DeleteAdminRequest struct {
	Id uint `json:"id" validate:"required"`
}

// @Summary 删除管理员账号
// @Description 删除管理员
// @Tags 管理员
// @Accept application/json
// @Produce application/json
// @param Accept-Version header string true "1.0.0"
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param param body DeleteAdminRequest true "删除管理员账号参数"
// @Success 200 {object} utils.Response --> 成功后返回数据结构
// @Failure 400 {object} utils.ResponseError --> 失败后返回数据结构
// @Router /admin/system_admin/del [post]
func DeleteAdminHandler(ctx iris.Context) {
	var RequestParams DeleteAdminRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var claims services.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	var common dao.Common[dao.SystemAdmin]
	if _, err := common.First(map[string]interface{}{"id": RequestParams.Id}); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		/*if claims.Type >= admin.AdminType {
			ctx.JSON(utils.ResponseError{Code: 403, Message: "无法修改，权限不够！"})
			return
		} else {*/
		var adminServe services.SystemAdminService
		if err := adminServe.RemoveAdmin(RequestParams.Id); err != nil {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
			return
		} else {
			ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: "ok"})
			return
		}
		//}
	}
}

//权限控制

func AccessHandler(ctx iris.Context) {
	var claims services.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}

	/*switch claims.Type {
	case 0:
		ctx.Next()
	case 1:
		if strings.Contains(ctx.FullRequestURI(), "api/static") {
			ctx.Next()
		}
		//副管理员权限控制
		uris := strings.Split(ctx.FullRequestURI(), "/api/admin")
		if len(uris) == 2 {
			//rule := []string{"/system_admin/created", "/user/excel/batch_update", "/user/excel/imports", "/project/status/edit", "/project/del"}
			rule := []string{"/system_admin/created", "/project/status/edit", "/project/del"}
			if arrays.ContainsString(rule, uris[1]) > -1 {
				ctx.JSON(utils.ResponseError{Code: iris.StatusNotAcceptable, Message: "权限不够"})
				return
			}
			ctx.Next()
		} else {
			ctx.JSON(utils.ResponseError{Code: iris.StatusBadRequest, Message: iris.StatusText(iris.StatusBadRequest)})
			return
		}

	case 2:
		ctx.JSON(utils.ResponseError{Code: 406, Message: "权限不够"})
		return
	default:
		ctx.JSON(utils.ResponseError{Code: 406, Message: "权限不够"})
		return
	}*/
	ctx.Next()
}

type AddSystemAdminTypeRequest struct {
	AdminTypeName     string `json:"admin_type_name" validate:"required"`     //管理员类型名
	AdminTypeDescribe string `json:"admin_type_describe" validate:"required"` //管理员类型描述
	Ids               string `json:"ids" validate:"required"`                 //权限ID,用,分隔
}

func AddSystemAdminTypeHandler(ctx iris.Context) {
	var RequestParams AddSystemAdminTypeRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var claims services.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}

	var admindao dao.Common[dao.SystemAdminType]
	var record dao.SystemAdminType
	record.AdminTypeName = RequestParams.AdminTypeName
	record.AdminTypeDescribe = RequestParams.AdminTypeDescribe
	if err := admindao.CreateOneReturnId(&record).Error; err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		if utils.StringIsNotEmpty(RequestParams.Ids) {
			var id = record.Id
			var systemAdminPermissionsObjs []dao.SystemAdminPermission
			permissionIds := strings.Split(RequestParams.Ids, ",")
			for _, permission := range permissionIds {
				var systemAdminPermissionsObj dao.SystemAdminPermission
				systemAdminPermissionsObj.AdminTypeId = id
				systemAdminPermissionsObj.PermissionId, _ = utils.StringToUint(permission)
				systemAdminPermissionsObjs = append(systemAdminPermissionsObjs, systemAdminPermissionsObj)
			}
			var systemAdminPermissionDao dao.Common[dao.SystemAdminPermission]
			if err := systemAdminPermissionDao.Create(systemAdminPermissionsObjs).Error; err != nil {
				ctx.JSON(utils.ResponseServerError(err))
				return
			}
		}
	}
	ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: "ok"})
	return
}

type EditSystemAdminTypeRequest struct {
	Id                uint   `json:"id" validate:"required"`                  //主键
	AdminTypeName     string `json:"admin_type_name" validate:"required"`     //管理员类型名
	AdminTypeDescribe string `json:"admin_type_describe" validate:"required"` //管理员类型描述
	Ids               string `json:"ids" validate:"required"`                 //权限ID,用,分隔
}

func EditSystemAdminTypeHandler(ctx iris.Context) {
	var RequestParams EditSystemAdminTypeRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var claims services.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}

	var admindao dao.Common[dao.SystemAdminType]
	set := map[string]interface{}{"admin_type_name": RequestParams.AdminTypeName, "admin_type_describe": RequestParams.AdminTypeDescribe}
	if err := admindao.UpdateOne(RequestParams.Id, set).Error; err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		if utils.StringIsNotEmpty(RequestParams.Ids) {
			var id = RequestParams.Id
			var systemAdminPermissionsObjs []dao.SystemAdminPermission
			permissionIds := strings.Split(RequestParams.Ids, ",")
			for _, permission := range permissionIds {
				var systemAdminPermissionsObj dao.SystemAdminPermission
				systemAdminPermissionsObj.AdminTypeId = id
				systemAdminPermissionsObj.PermissionId, _ = utils.StringToUint(permission)
				systemAdminPermissionsObjs = append(systemAdminPermissionsObjs, systemAdminPermissionsObj)
			}
			var systemAdminPermissionDao dao.Common[dao.SystemAdminPermission]
			if err := systemAdminPermissionDao.DeleteByStringColumn("admin_type_id", utils.UintToString(id)).Error; err != nil {
				ctx.JSON(utils.ResponseServerError(err))
				return
			} else {
				if err := systemAdminPermissionDao.Create(systemAdminPermissionsObjs).Error; err != nil {
					ctx.JSON(utils.ResponseServerError(err))
					return
				}
			}
		}
	}
	ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: "ok"})
	return
}

type DelSystemAdminTypeRequest struct {
	Id uint `json:"id" validate:"required"` //主键
}

func DelSystemAdminTypeHandler(ctx iris.Context) {
	var RequestParams DelSystemAdminTypeRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var claims services.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	var adminDao dao.Common[dao.SystemAdmin]
	if count, err := adminDao.Count(map[string]interface{}{"admin_type": RequestParams.Id}); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		if count > 0 {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: "该类型下存在管理员，无法删除!"})
			return
		}

		var adminTypeDao dao.Common[dao.SystemAdminType]
		if err := adminTypeDao.DeleteById(RequestParams.Id).Error; err != nil {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
			return
		} else {
			var systemAdminPermissionDao dao.Common[dao.SystemAdminPermission]
			if err := systemAdminPermissionDao.DeleteByStringColumn("admin_type_id", utils.UintToString(RequestParams.Id)).Error; err != nil {
				ctx.JSON(utils.ResponseServerError(err))
				return
			}
		}

		ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: "ok"})
		return
	}
}

type SystemAdminTypeDetailRequest struct {
	Id uint `json:"id" validate:"required"` //主键
}

func SystemAdminTypeDetailHandler(ctx iris.Context) {
	var RequestParams SystemAdminTypeDetailRequest

	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var claims services.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}

	var systemPermissionDao dao.Common[dao.SystemPermission]
	if systemPermission, err := systemPermissionDao.FindAll(map[string]interface{}{}); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		var systemAdminPermissionDao dao.Common[dao.SystemAdminPermission]
		if systemAdminPermission, err := systemAdminPermissionDao.FindAll(map[string]interface{}{"admin_type_id": RequestParams.Id}); err != nil {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
			return
		} else {
			var sysAdminTypeDao dao.Common[dao.SystemAdminType]
			if adminType, err := sysAdminTypeDao.First(map[string]interface{}{"id": RequestParams.Id}); err != nil {
				ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
				return
			} else {
				ctx.JSON(utils.Response{Code: iris.StatusOK, Message: "ok", Data: iris.Map{"adminType": adminType, "permission": systemPermission, "admin_permission": systemAdminPermission}})
				return
			}
		}
	}
	/*var adminTypeDao dao.Common[dao.SystemAdminType]
	if adminType, err := adminTypeDao.First(map[string]interface{}{"id": RequestParams.Id}); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {

	}*/
}

type SystemAdminTypeListRequest struct {
	Page     int64 `json:"page" validate:"required"`
	PageSize int64 `json:"page_size" validate:"required"`
}

func SystemAdminTypeListlHandler(ctx iris.Context) {
	var RequestParams IncomeQueryRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var systemAdminServe services.SystemAdminService
	if total, res, err := systemAdminServe.SystemAdminTypeList(RequestParams.Page, RequestParams.PageSize); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		ctx.JSON(utils.Response{Code: iris.StatusOK, Message: "ok", Data: iris.Map{"count": total, "list": res}})
		return
	}
}

func SystemPermissionListlHandler(ctx iris.Context) {
	var systemPermissionDao dao.Common[dao.SystemPermission]
	if systemPermission, err := systemPermissionDao.FindAll(map[string]interface{}{}); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		ctx.JSON(utils.Response{Code: iris.StatusOK, Message: "ok", Data: iris.Map{"permission": systemPermission}})
		return
	}
}
